package com.xinchuang.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xinchuang.util.AreaUtil;
import org.apache.commons.lang3.StringUtils;
import org.geotools.referencing.CRS;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;

import javax.json.Json;
import java.io.*;
import java.util.*;

/**
 * TODO
 *
 * @author zkwczx
 * @version 1.0
 * @date 2023/11/9 15:00
 */
public class MyUtil {

    private static final String class_verity = "[";

    private static final String image_verity = ",";

    public static String classToString(String classify) {
        if (classify.contains(class_verity)) {
            JSONArray array = JSONArray.parseArray(classify);
            return array.getString(array.size() - 1);
        }
        return classify;
    }

    public static String verityString(String str) {
        if (StringUtils.isNotBlank(str)) {
            return str;
        }
        return "";
    }

    public static boolean base64ToImage(String imageData, String url) {
        try {
            if (imageData.contains(image_verity)) {
                imageData = imageData.split(image_verity)[1];
            }
            // 将Base64字符串解码为字节数组
            byte[] imageBytes = Base64.getDecoder().decode(imageData);
            // 创建输出流，将字节数组写入到图片文件
            FileOutputStream outputStream = new FileOutputStream(url);
            outputStream.write(imageBytes);
            // 关闭输出流
            outputStream.close();
            System.out.println("图片保存成功！");
        } catch (IOException e) {
            System.out.println("保存图片失败：" + e.getMessage());
            return false;
        }
        return true;
    }

    public static boolean autoWin(String exeUrl, String baseUrl, String projectUrl, String fileName) {
        System.out.println("启动指令：" + exeUrl + " " + baseUrl + "TargetList.txt" + " " + baseUrl + "RefList.txt" + " " + projectUrl);
        // 创建参数列表
        List<String> commands = new ArrayList<>();
        commands.add(exeUrl);
        commands.add(baseUrl + "TargetList.txt");
        commands.add(baseUrl + "RefList.txt");
        commands.add(projectUrl);
        try {
            // 创建ProcessBuilder实例并设置命令及参数
            ProcessBuilder pb = new ProcessBuilder(commands);
            // 可选设置工作目录等其他属性
            pb.directory(new File(projectUrl));

            // 启动进程
            Process process = pb.start();

            // 处理进程的输出与错误流类似上面的方法
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待进程结束并获取退出码
            int exitCode = process.waitFor();
            if (FileUtil.newFile(projectUrl + fileName + "_REG.tif").isFile()) {
                return true;
            }
            System.out.println("Process exited with code " + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static JSONArray toRectangle(JSONArray array) {
        Double minLng = 0.0;
        Double maxLng = 0.0;
        Double minLat = 0.0;
        Double maxLat = 0.0;
        minLng = array.getJSONArray(0).getDouble(0);
        if (minLng > array.getJSONArray(1).getDouble(0)) {
            maxLng = minLng;
            minLng = array.getJSONArray(1).getDouble(0);
        } else {
            maxLng = array.getJSONArray(1).getDouble(0);
        }
        minLat = array.getJSONArray(0).getDouble(1);
        if (minLat > array.getJSONArray(1).getDouble(1)) {
            maxLat = minLat;
            minLat = array.getJSONArray(1).getDouble(1);
        } else {
            maxLat = array.getJSONArray(1).getDouble(1);
        }
        JSONArray main = new JSONArray();
        JSONArray one = new JSONArray();
        JSONArray two = new JSONArray();
        one.add(minLng);
        one.add(maxLat);
        one.add(0);
        two.add(maxLng);
        two.add(minLat);
        two.add(0);
        main.add(one);
        main.add(two);
        return main;
    }

    public static JSONObject toDiscern(JSONArray array) {
        JSONObject json = new JSONObject();
        Double minLng = 0.0;
        Double maxLng = 0.0;
        Double minLat = 0.0;
        Double maxLat = 0.0;
        minLng = array.getJSONArray(0).getDouble(0);
        if (minLng > array.getJSONArray(1).getDouble(0)) {
            maxLng = minLng;
            minLng = array.getJSONArray(1).getDouble(0);
        } else {
            maxLng = array.getJSONArray(1).getDouble(0);
        }
        minLat = array.getJSONArray(0).getDouble(1);
        if (minLat > array.getJSONArray(1).getDouble(1)) {
            maxLat = minLat;
            minLat = array.getJSONArray(1).getDouble(1);
        } else {
            maxLat = array.getJSONArray(1).getDouble(1);
        }
        JSONArray main = new JSONArray();
        JSONArray one = new JSONArray();
        JSONArray two = new JSONArray();
        one.add(minLng);
        one.add(maxLat);
        one.add(0);
        two.add(maxLng);
        two.add(minLat);
        two.add(0);
        main.add(one);
        main.add(two);
        json.put("positions", main);
        json.put("type", "rectangle");
        Double length = AreaUtil.getDistance(maxLat, minLng, maxLat, maxLng);
        Double width = AreaUtil.getDistance(maxLat, minLng, minLat, minLng);
        Double middle;
        if (width > length) {
            middle = width;
            width = length;
            length = middle;
        }
        json.put("length", length);
        json.put("width", width);
        return json;
    }

    public static String fromWeb(String type) {
        switch (type) {
            case "SMGeoRectangle":
                return "rectangle";
            case "CzmCircleGroundPrimitive":
                return "round";
            case "XbsjObliqueRectangle":
                return "skewrectangle";
            case "XbsjObliqueRectangle-GeoPolygon":
                return "GeoPolygon";
            default:
                return null;
        }
    }

    public static String toWeb(String type) {
        switch (type) {
            case "rectangle":
                return "SMGeoRectangle";
            case "round":
                return "CzmCircleGroundPrimitive";
            case "skewrectangle":
                return "XbsjObliqueRectangle";
            case "GeoPolygon":
                return "XbsjObliqueRectangle-GeoPolygon";
            default:
                return type;
        }
    }

    public static JSONObject webToJson(JSONObject webJson) {
        JSONObject jsonObject = new JSONObject();
        String type = fromWeb(webJson.getString("type"));
        if (null == type) {
            type = webJson.getString("type");
        }
        Double value = 0.0;
        JSONArray array = new JSONArray();
        if (CollectionUtil.isNotEmpty(webJson.getJSONArray("position"))) {
            array = webJson.getJSONArray("position");
        }
        if (CollectionUtil.isNotEmpty(webJson.getJSONArray("positions"))) {
            array = webJson.getJSONArray("positions");
        }
        if (ObjectUtil.isNotEmpty(webJson.getDouble("radius"))) {
            value = webJson.getDouble("radius");
        }
        jsonObject.put("list", array);
        jsonObject.put("type", type);
        jsonObject.put("value", value);
        return jsonObject;
    }

    public static JSONArray getBox(double minLng, double minLat, double maxLng, double maxLat) {
        JSONArray array = new JSONArray();

        JSONArray leftUp = new JSONArray();
        leftUp.add(minLng);
        leftUp.add(maxLat);
        leftUp.add(0.0);

        JSONArray rightUp = new JSONArray();
        rightUp.add(maxLng);
        rightUp.add(maxLat);
        rightUp.add(0.0);

        JSONArray rightDown = new JSONArray();
        rightDown.add(maxLng);
        rightDown.add(minLat);
        rightDown.add(0.0);

        JSONArray leftDown = new JSONArray();
        leftDown.add(minLng);
        leftDown.add(minLat);
        leftDown.add(0.0);

        array.add(leftUp);
        array.add(rightUp);
        array.add(rightDown);
        array.add(leftDown);
        return array;
    }

    public static String encryptPass(String userId) {
        // 生成秘钥
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        // 构建
        SymmetricCrypto symmetricCrypto = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        // 加密
        return symmetricCrypto.encryptHex(userId);
    }

    public static String decodePass(String ciphertext) {
        // 生成秘钥
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        // 构建
        SymmetricCrypto symmetricCrypto = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        // 解密
        return symmetricCrypto.decryptStr(ciphertext);
    }

    public static void main(String[] args) {
//        String str = " 我是123一段测abd试 空a格 的字符 串 ";
//        System.out.println("过滤出汉字：" + str.replaceAll("\\s*","").replaceAll("[^(\\u4e00-\\u9fa5)]",""));
//        String str = " 我是123一段测abd试 空a格 的字符 串 ";
//        System.out.println("过滤出字母：" + str.replaceAll("\\s*","").replaceAll("[^(A-Za-z)]",""));
//        String str = " 我是123一段测abd试 空a格 的字符 串 ";
//        System.out.println("过滤出数字：" + str.replaceAll("\\s*","").replaceAll("[^(0-9)]",""));
//        String str = " 我是123一段测abd试 空a格 的字符 串 ";
//        System.out.println("过滤出数字+字母：" + str.replaceAll("\\s*","").replaceAll("[^(a-zA-Z0-9)]",""));
//        String str1 = " 我是一段测试 空格 的字符 串 ";
//        String str2 = " 我是一段测试 空格 的字符 串 ";
//        String str3 = " 我是一段测试 \r空格 的字符 串 ";
//        String str4 = " 我是一段测试 \r空格 的字符 串 ";
//        String str5 = " 我是一段测试 \t空格 \r的字\n符 串 ";
//        //去掉首尾空格
//        System.out.println("去掉首尾空格：" + str1.trim());
//        //去掉所有空格
//        System.out.println("去掉所有空格：" + str2.replace(" ",""));
//        System.out.println("去掉所有空格：" + str3.replaceAll(" ",""));
//        System.out.println("去掉所有空格：" + str4.replaceAll(" +",""));
//        //去掉特殊的空格、制表符、换页符
//        System.out.println("去掉特殊的空格、制表符、换页符：" + str5.replaceAll("\\s*",""));
    }

    public static String getStrChinese(String str) {
        StringBuffer sb = new StringBuffer();
        char[] chars = str.toCharArray();
        boolean isCh = false;
        for (int i = 0; i < chars.length; i++) {
            if (isChinese(chars[i])) {
                if (!isCh) {
                    isCh = true;
                }
                if (sb.length() == 0) {
                    if (chars[i] == '东' || chars[i] == '南' || chars[i] == '西' || chars[i] == '北') {
                        continue;
                    }
                }
                sb.append(chars[i]);
            } else {
                if (isCh) {
                    break;
                }
            }
        }
        return sb.toString();
    }

    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS;
    }

    public static String getRandomStr(int length) {
        String[] str = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
                "V", "W", "X", "Y", "Z",
                "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
                "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append(str[RandomUtil.randomInt(0, str.length)]);
        }
        return sb.toString();
    }

}
